<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>用户注册</h2>
        <p>数据标注大屏后台管理系统</p>
      </div>
      <el-form :model="registerForm" :rules="rules" ref="registerForm" class="register-form">
        <!-- 邀请码 -->
        <el-form-item prop="inviteCode">
          <el-input
            v-model="registerForm.inviteCode"
            placeholder="请输入邀请码"
            prefix-icon="el-icon-key"
            autocomplete="off"
            maxlength="20"
          ></el-input>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名（3-20个字符）"
            prefix-icon="el-icon-user"
            autocomplete="off"
            maxlength="20"
            @blur="checkUsername"
          >
            <template slot="suffix" v-if="usernameCheckResult">
              <span v-if="usernameCheckResult === 'available'" class="check-success">
                <i class="el-icon-circle-check"></i> 用户名可用
              </span>
              <span v-else-if="usernameCheckResult === 'exists'" class="check-error">
                <i class="el-icon-circle-close"></i> 用户名已存在
              </span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码（6-20个字符）"
            prefix-icon="el-icon-lock"
            autocomplete="off"
            maxlength="20"
          >
            <i
              slot="suffix"
              :class="showPassword ? 'el-icon-view' : 'el-icon-view'"
              class="password-toggle"
              @click="showPassword = !showPassword"
            ></i>
          </el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            :type="showConfirmPassword ? 'text' : 'password'"
            placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"
            autocomplete="off"
            maxlength="20"
            @keyup.enter.native="handleRegister"
          >
            <i
              slot="suffix"
              :class="showConfirmPassword ? 'el-icon-view' : 'el-icon-view'"
              class="password-toggle"
              @click="showConfirmPassword = !showConfirmPassword"
            ></i>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleRegister"
            class="register-button"
          >
            {{ loading ? '注册中...' : '注 册' }}
          </el-button>
        </el-form-item>

        <div class="register-footer">
          <el-button type="text" @click="goToLogin">已有账号？去登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import 'element-ui/lib/theme-chalk/index.css';
import { registerAPI, checkUsernameAPI } from '@/api/admin';

// 固定邀请码
const VALID_INVITE_CODE = 'AAAaaa1234@';

export default {
  name: 'Register',
  data() {
    // 验证邀请码
    const validateInviteCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邀请码'));
      } else if (value !== VALID_INVITE_CODE) {
        callback(new Error('邀请码错误'));
      } else {
        callback();
      }
    };

    // 验证用户名格式
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'));
      } else if (value.length < 3) {
        callback(new Error('用户名长度不能少于3个字符'));
      } else if (value.length > 20) {
        callback(new Error('用户名长度不能超过20个字符'));
      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        callback(new Error('用户名只能包含字母、数字和下划线'));
      } else if (this.usernameCheckResult === 'exists') {
        callback(new Error('用户名已存在'));
      } else {
        callback();
      }
    };

    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      registerForm: {
        inviteCode: '',
        username: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        inviteCode: [
          { required: true, validator: validateInviteCode, trigger: 'blur' }
        ],
        username: [
          { required: true, validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      loading: false,
      showPassword: false,
      showConfirmPassword: false,
      usernameCheckResult: null // 'available' | 'exists' | null
    };
  },
  methods: {
    // 检查用户名是否存在
    checkUsername() {
      const username = this.registerForm.username;
      if (!username || username.length < 3 || username.length > 20 || !/^[a-zA-Z0-9_]+$/.test(username)) {
        this.usernameCheckResult = null;
        return;
      }

      checkUsernameAPI(username).then(res => {
        if (res.code === 200) {
          this.usernameCheckResult = res.data.exists ? 'exists' : 'available';
          // 触发表单验证
          this.$refs.registerForm.validateField('username');
        }
      }).catch(error => {
        console.error('检查用户名错误:', error);
        this.usernameCheckResult = null;
      });
    },

    // 处理注册
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          // 如果用户名已存在，不允许注册
          if (this.usernameCheckResult === 'exists') {
            this.$message.error('用户名已存在，请更换用户名');
            return;
          }

          this.loading = true;
          const data = {
            username: this.registerForm.username,
            password: this.registerForm.password,
            inviteCode: this.registerForm.inviteCode
          };

          registerAPI(data).then(res => {
            this.loading = false;
            if (res.code === 200) {
              this.$message.success('注册成功，请登录');
              // 跳转到登录页面
              this.$router.push('/admin/login');
            } else {
              this.$message.error(res.message || '注册失败');
            }
          }).catch(error => {
            this.loading = false;
            this.$message.error('注册失败，请检查网络或联系管理员');
            console.error('注册错误:', error);
          });
        }
      });
    },

    // 去登录
    goToLogin() {
      this.$router.push('/admin/login');
    }
  },
  watch: {
    // 监听用户名变化，重置检查结果
    'registerForm.username'(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.usernameCheckResult = null;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.register-container {
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
    background-size: 50px 50px;
    animation: move 20s linear infinite;
  }

  @keyframes move {
    0% {
      transform: translate(0, 0);
    }
    100% {
      transform: translate(50px, 50px);
    }
  }
}

.register-box {
  width: 450px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;

  h2 {
    margin: 0 0 10px;
    font-size: 28px;
    color: #333;
    font-weight: 600;
  }

  p {
    margin: 0;
    font-size: 14px;
    color: #999;
  }
}

.register-form {
  :deep(.el-input__inner) {
    height: 45px;
    line-height: 45px;
    border-radius: 6px;
    padding-right: 120px; // 为后缀图标留空间
  }

  :deep(.el-input__prefix) {
    line-height: 45px;
  }

  :deep(.el-input__suffix) {
    line-height: 45px;
    right: 10px;
  }

  .check-success {
    color: #67c23a;
    font-size: 12px;
    white-space: nowrap;
    
    i {
      margin-right: 3px;
    }
  }

  .check-error {
    color: #f56c6c;
    font-size: 12px;
    white-space: nowrap;
    
    i {
      margin-right: 3px;
    }
  }

  .password-toggle {
    cursor: pointer;
    color: #909399;
    font-size: 16px;
    
    &:hover {
      color: #409EFF;
    }
  }
}

.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 6px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  
  &:hover {
    background: linear-gradient(135deg, #5568d3 0%, #6a4093 100%);
  }
}

.register-footer {
  text-align: center;
  margin-top: 20px;
}
</style>
